//
//  JWTMysViewController.m
//  JWT
//
//  Created by Apple on 2017/1/1.
//  Copyright © 2017年 com.jwtsoft. All rights reserved.
//

#import "JWTMysViewController.h"
#import "JWTRegisterViewController.h"
#import "JWTUserHeaderView.h"
#import "JWTUserDetailCell.h"

#import "JWTUpdateUserInfoViewController.h"//修改个人中心
#import "JWTAboutJWTViewController.h"
#import "JWTMyCourseRecodesViewController.h"
#import "JWTUserChargeMemberViewController.h"

@interface JWTMysViewController ()<UITableViewDelegate,UITableViewDataSource,UIActionSheetDelegate>

@property (nonatomic,strong) UIScrollView *scrollView;

@property (nonatomic,strong) UITableView *tableView;

@property (nonatomic,strong) JWTUserHeaderView *userHeaderView;

@property (nonatomic,strong) NSArray *hintSecArray;

@property (nonatomic,strong) NSArray *hintRowArray;

@end

static NSString *JWTUserDetailCell_Identifier = @"JWTUserDetailCell_Identifier";

@implementation JWTMysViewController

-(instancetype)init{
    self = [super init];
    if (self) {
       self.title = @"个人中心";
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _hintSecArray = @[@"个人",@"关于",@"设置"];
    _hintRowArray = @[@[@"我的资料",@"我的课程",@"我的VIP"],@[@"关于金舞团"],@[@"清除缓存",@"注销"]];
    
    [self initWithTableView];

    
    //刷新页面数据！
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadData_UserInfoNoticeAction:) name:@"ReloadData_UserInfoNoticeAction" object:nil];
    
    if (APPDELEGATE.userInfo) {
        [self reloadData];
        self.userHeaderView.userInfo = APPDELEGATE.userInfo;
    }
}

-(void) reloadData_UserInfoNoticeAction:(NSNotification *)notice{
    [self reloadData];
    self.userHeaderView.userInfo = APPDELEGATE.userInfo;
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

/**
 刷新用户详情数据
 */
-(void) reloadData{
//    NSString *urlString = [[JWTAPPHttpsUrl sharedInstance] getUserDetailInfoWithActionUserMessage];
//    [HUD showUIBlockingIndicator];
//    [AFNHttpsRequest requestWithUrl:urlString WithParam:nil WithGetDataDidFinishBlock:^(id model, NSURLSessionDataTask *task, NSError *error) {
//        [HUD hideUIBlockingIndicator];
//        if (model) {
//            if ([[model objectForKey:@"code"]integerValue] == 200) {
//                NSLog(@"%@",[model objectForKey:@"data"]);
//                
//                [_tableView reloadData];
//            }
//        }
//    }];
    [_tableView reloadData];
}


-(void) initWithTableView{
    if (_tableView == nil) {
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0,UISCREEN_WIDTH , UISCREEN_HEIGHT-getNAVI_TOP_HEIGHT()-getTABBar_bottom_HEIGHT()-Cell_Margin)];
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.backgroundColor = RGB_LightGrayBackGround;
        [self.view addSubview:tableView];
        [tableView registerClass:[JWTUserDetailCell class] forCellReuseIdentifier:JWTUserDetailCell_Identifier];
        _userHeaderView = [JWTUserHeaderView sharedInstance];
        tableView.tableHeaderView = _userHeaderView;
        _tableView = tableView;
    }
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _hintSecArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0)
        return [[_hintRowArray objectAtIndex:0] count];
    else if(section == 1){
        return [[_hintRowArray objectAtIndex:1] count];
    }else if (section == 2){
        return [[_hintRowArray objectAtIndex:2] count];
    }else
        return 0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    JWTUserDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:JWTUserDetailCell_Identifier forIndexPath:indexPath];
    cell.hintNameLabel.text = [[_hintRowArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    
//    if (indexPath.section == 0) {
    
//    }else if (indexPath.section == 1){
    
//    }else if (indexPath.section == 2){
//        
//    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            JWTUpdateUserInfoViewController *vc = [[JWTUpdateUserInfoViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }else if (indexPath.row == 1){
            JWTMyCourseRecodesViewController *vc  = [[JWTMyCourseRecodesViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }else if (indexPath.row == 2){
            JWTUserChargeMemberViewController *vc  = [[JWTUserChargeMemberViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }else if (indexPath.section == 1){
        JWTAboutJWTViewController *vc = [[JWTAboutJWTViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }else if (indexPath.section == 2){
        if (indexPath.row == 0) {
            // 清理缓存
            NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
            CGFloat cacheContentSize = [self folderSizeAtPath:cachePath];
            
            NSString *hint = [NSString stringWithFormat:@"缓存大小为%.2fM,确定要清理缓存吗？",cacheContentSize];
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:hint preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self clearCacheWithMemory];
                
                [HUD showToast:@"清理完成"];
                
                [self.tableView reloadData];
            }]];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                ;
            }]];
            
            [self presentViewController:alert animated:YES completion:nil];
        } else if (indexPath.row == 1) {
            UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"您确定退出当前程序吗?" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"确定", nil];
            [sheet showInView:self.view];
        }
    }
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        return;
    }else{
        APPDELEGATE.userInfo = nil;
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:@"" forKey:@"tel"];
        [userDefaults setObject:@"" forKey:@"userName"];
        [userDefaults setObject:@"" forKey:@"passWord"];
        [userDefaults setObject:@"" forKey:@"tokenID"];
        [userDefaults synchronize];
        APPDELEGATE.isLogin = NO;
        [self.view addSubview:[JWTLoginCoverView sharedInstance]];
        
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, 0, UISCREEN_WIDTH, 44);
    headerView.backgroundColor = RGB_WhiteBackGround;
    UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(headerView.left+8, headerView.top, UISCREEN_WIDTH-16, 44)];
    headerLabel.text = [_hintSecArray objectAtIndex:section];
    [headerLabel setNumberOfLines:0];
    [headerLabel setFont:[UIFont systemFontOfSize:13.5f]];
    headerLabel.textColor = RGB_DarkGray;
    headerLabel.text = [_hintSecArray objectAtIndex:section];
    [headerView addSubview:headerLabel];
    
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static JWTUserDetailCell *cell = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        cell = [tableView dequeueReusableCellWithIdentifier:JWTUserDetailCell_Identifier];
    });
    return cell.height;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 44;
}
- (void)viewWillAppear:(BOOL)animated{
    [[self rdv_tabBarController] setTabBarHidden:NO animated:YES];
    self.navigationImageView.hidden = YES;
    if (APPDELEGATE.isLogin == NO) {
        JWTLoginCoverView *loginView = [JWTLoginCoverView sharedInstance];
        [self.view addSubview:loginView];
    }else{ // 已经登录，移除 JWTLoginCoverView
        JWTLoginCoverView *loginView = [JWTLoginCoverView sharedInstance];
        [loginView removeFromSuperview];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 计算缓存文件大小
/**
 *  遍历文件夹获得文件夹大小，返回多少M
 */
- (float )folderSizeAtPath:(NSString*) folderPath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize/(1024.0*1024.0);
}

/**
 *  单个文件的大小
 *
 *  @param filePath 文件路径
 */
- (long long)fileSizeAtPath:(NSString*) filePath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

#pragma mark - 清除缓存
- (void)clearCacheWithMemory {
    
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachePath];
    
    for (NSString *p in files) {
        
        NSError *error;
        
        NSString *path = [cachePath stringByAppendingPathComponent:p];
        
        if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
            
            [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
        }
    }
}

@end
